package com.hugh.dubbo.filter;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ListenableFilter;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Hugh
 * @Date: 2020/7/4
 */
@Slf4j
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER}, value = "transportIPFilter", order = 1)
public class TransportIPFilter extends ListenableFilter {

    private static String TRANSPORT_IP_KEY = "transport_ip_key";

    @Override
    @SneakyThrows
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        RpcContext context = RpcContext.getContext();
        boolean providerSide = context.isProviderSide();
        if(providerSide){
            String remoteIp = context.getAttachment(TRANSPORT_IP_KEY);
            String serviceMethod = context.getUrl().getServiceInterface() + context.getMethodName();
            log.info("TransportIPFilter:本次provider端被调用的方法是:{}, 调用ip是:{}", serviceMethod, remoteIp);
        }

        boolean consumerSide = context.isConsumerSide();
        if(consumerSide){
            Map<String, String> attachment = new HashMap<>();
            String localIp = getLocalIp();
            attachment.put(TRANSPORT_IP_KEY, localIp);
            context.setAttachments(attachment);
//            log.info("TransportIPFilter: 消费端开始调用");
        }
        return invoker.invoke(invocation);
    }

    private String getLocalIp() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();
    }
}
